package cn.xspace.wnx.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;

import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.HypyUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.MyListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.ChatInfoActivity;
import cn.xspace.wnx.activity.SelectMemberActivity;
import cn.xspace.wnx.adapter.ContactListAdapter;
import cn.xspace.wnx.db.OrgAllUserDao;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/10/28.
 */

public class AddressBookSelectFragment extends BaseFragment {
    private static final String TAG = "AddressBookSelectFragme";
    private ArrayList<OrgDeptUserBean> dataList = new ArrayList<>();
    private MyListView dataListview;
    private ContactListAdapter mAdapter;
    private String user_id = "";
    private String dept_id = "";
    private String fromType = "";
    private String groupOwner = "";
    private ArrayList<String> memberIdList = new ArrayList<>();


    public static AddressBookSelectFragment newInstance(ArrayList<OrgDeptUserBean> dataList, String fromType, String
            ownerId) {
        Bundle args = new Bundle();
        args.putSerializable(SelectMemberActivity.SELECTED_MEMBERS, dataList);
        args.putSerializable(ChatInfoActivity.GROUP_OWNER, ownerId);
        args.putString(ChatInfoActivity.KEY_MEMBER_OPERATE, fromType);
        AddressBookSelectFragment fragment = new AddressBookSelectFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
        user_id = MyInfoUtil.getMyUserid(mContext);
        dept_id = MyInfoUtil.getUseOrgId(mContext);
        fromType = fragmentArgs.getString(ChatInfoActivity.KEY_MEMBER_OPERATE);
        groupOwner = fragmentArgs.getString(ChatInfoActivity.GROUP_OWNER);
    }

    @Override
    public View initView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_addressbook_list_select, null);
    }

    @Override
    protected void initFindViewById(View view) {
        dataListview = (MyListView) view.findViewById(R.id.listview_addressbook);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void initData() {
        mAdapter = new ContactListAdapter(mContext, dataList, null, true);
        if (isMinMember() || isAddMember()) { //如果是添加人员或者是删除人员
            ArrayList<OrgDeptUserBean> memberList = (ArrayList<OrgDeptUserBean>) fragmentArgs.getSerializable
                    (SelectMemberActivity.SELECTED_MEMBERS);
            memberIdList = new ArrayList<>();
            if (memberList != null) {
                for (OrgDeptUserBean bean : memberList) {
                    if (isMinMember()) {
                        bean.isSelectd = false;
                    } else {
                        bean.isSelectd = true;
                    }
                    memberIdList.add(bean.user_id);
                }
                if (isMinMember()) { //删除人员只需要传递过来的数据集合即可,不用再单独加载数据,所以此处return
                    dataList.addAll(memberList);
                    mAdapter.setShowAlphea(false);
                    mAdapter.setGroupOwnerId(groupOwner);
                    mAdapter.setiOrgUserCheckListener(listener);
                    dataListview.setAdapter(mAdapter);
                    mAdapter.notifyDataSetChanged();
                    return;
                }
            }
        }
        mAdapter.setShowAlphea(true);
        mAdapter.setiOrgUserCheckListener(listener);
        dataListview.setAdapter(mAdapter);
//        Message msg = mHander.obtainMessage();

        getLocalData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        dataListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OrgDeptUserBean bean = dataList.get(position);
                if (isAddMember()) {
                    if (memberIdList.contains(bean.user_id)) { //如果点击的是群组本身的人,不做处理,防止点击后取消了该用户的选择
                        LogUtil.d(TAG, "wubaojie>>>onItemClick: user_name:" + bean.user_name + "已在群组,不能更改");
                        return;
                    }
                } else if (isMinMember()) {
                    if (bean.user_id.equals(groupOwner)) {
                        //群主不能删除
                        T.showShort(mContext, R.string.group_owner_delete_not);
                        return;
                    }
                }
                View checkbox = view.findViewById(R.id.check_select);
                if (checkbox != null && checkbox instanceof CheckBox) {
                    if (user_id.equals(bean.user_id)) {
                        LogUtil.d(TAG, "wubaojie>>>onItemClick: user_name:" + bean.user_name + "是我自己");
                        return;
                    }
                    boolean state = ((CheckBox) checkbox).isChecked();
                    ((CheckBox) checkbox).setChecked(!state);
                    listener.orgUserCheck(position, dataList.get(position), !state);
                } else {
                    LogUtil.d("找不到checkbox");
                }
            }
        });
    }

    /**
     * 判断是否为删除员工
     *
     * @return
     */
    private boolean isMinMember() {
        if (ChatInfoActivity.MEMBER_MIN.equals(fromType)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为添加员工
     *
     * @return
     */
    private boolean isAddMember() {
        if (ChatInfoActivity.MEMBER_ADD.equals(fromType)) {
            return true;
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.d("onResume");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        LogUtil.d("setUserVisibleHint");
//        if (isVisibleToUser && !isGetData) {
//            showDialog("正在加载");
//            //			queryWorTodoDetail();
//            Message message = mHandler.obtainMessage(0);
//            mHandler.sendMessageDelayed(message, 0);
//        }
    }

    /**
     * 获取数据
     */
    private void getLocalData() {
        LogUtil.d(TAG, "wubaojie>>>getLocalData: ");
        //获取本地数据
        showWaitDialog();
        registerSubscription(OrgAllUserDao.getInstance().getOrgUserData().getOrgUserList()
                .subscribeOn(Schedulers.io())
                .doOnNext(new Action1<List<OrgDeptUserBean>>() {
                    @Override
                    public void call(List<OrgDeptUserBean> orgDeptUserBeenList) {
                        for (OrgDeptUserBean bean : orgDeptUserBeenList) {
                            bean.shotKey = HypyUtil.cn2py(bean.user_name);
                        }
                        Collections.sort(orgDeptUserBeenList, new Comparator<OrgDeptUserBean>() {
                            @Override
                            public int compare(OrgDeptUserBean lhs, OrgDeptUserBean rhs) {
                                if (TextUtils.isEmpty(lhs.shotKey)) {
                                    return -1;
                                }
                                String key1 = lhs.shotKey.toUpperCase();
                                Integer num1 = HypyUtil.chartSortMap.get(key1);
                                String key2 = rhs.shotKey.toUpperCase();
                                Integer num2 = HypyUtil.chartSortMap.get(key2);
                                if (num1 == null) {
                                    return -1;
                                }
                                if (num2 == null) {
                                    return 1;
                                }
                                return num1.compareTo(num2);
                            }
                        });
                    }
                })
                .doOnNext(new Action1<List<OrgDeptUserBean>>() {
                    @Override
                    public void call(List<OrgDeptUserBean> orgDeptUserBeens) {
                        if (memberIdList != null && memberIdList.size() > 0) {
                            for (OrgDeptUserBean bean : orgDeptUserBeens) {
                                if (memberIdList.contains(bean.user_id)) {
                                    bean.isSelectd = true;
                                    bean.isCheckBoxEnable = false;
                                }
                            }
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OrgDeptUserBean>>() {
                    @Override
                    public void onCompleted() {

                        hideWaitDialog();
                        LogUtil.d(TAG, "onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        hideWaitDialog();
                        LogUtil.d(TAG, "onError");
                        //网络请求出错读取数据库
                    }

                    @Override
                    public void onNext(List<OrgDeptUserBean> o) {
                        hideWaitDialog();
                        LogUtil.d(TAG, "onNext>>>" + o.size());
                        for (OrgDeptUserBean bean : o) {
                            LogUtil.d(TAG, "onNext>>>>>>>>>" + bean.shotKey);
                        }
                        dataList.addAll(o);
                        dataListview.setAdapter(mAdapter);
                        mAdapter.notifyDataSetChanged();
                    }
                }));
    }

    /**
     * 通讯录checkBox被选择时的监听
     */
    ContactListAdapter.IOrgUserCheckListener listener = new ContactListAdapter.IOrgUserCheckListener() {
        @Override
        public void orgUserCheck(int position, OrgDeptUserBean bean, boolean isChecked) {
            LogUtil.d(bean.toString());
            if (isAddMember()) {
                if (memberIdList.contains(bean.user_id)) {
                    return;
                }
            } else if (isMinMember()) {
                if (bean.user_id.equals(groupOwner)) {
                    //群主不能删除
                    T.showShort(mContext, R.string.group_owner_delete_not);
                    return;
                }
            }

            bean.isSelectd = isChecked;
            //通知acitivity更新
            Map<String, Object> toActivityMap = new HashMap<>();
            toActivityMap.put(EventBusConstant.TYPE, EventBusConstant.ADDRESSBOOK_TO_ACTIVITY);
            toActivityMap.put(EventBusConstant.SINGLE_MEMBER, bean);
            toActivityMap.put(EventBusConstant.SELECT_OR_CANCEM, isChecked);
            EventBus.getDefault().post(toActivityMap);

            Map<String, Object> toFragmentMap = new HashMap<>();
            toFragmentMap.put(EventBusConstant.TYPE, EventBusConstant.ADDRESSBOOK_TO_ORGANIZATION);
            toFragmentMap.put(EventBusConstant.SELECT_OR_CANCEM, isChecked);
            toFragmentMap.put(EventBusConstant.OPERATE_ID, bean.user_id);
            EventBus.getDefault().post(toFragmentMap);
        }
    };

    /**
     * @param operateId
     * @param isSelectCancel
     */
    private void updateBeanById(String operateId, boolean isSelectCancel) {
        if (memberIdList.contains(operateId)) {
            return;
        }
        int cancelPosition = -1;
        if (!TextUtils.isEmpty(operateId)) { //要操作的id不为空
            for (OrgDeptUserBean bean : dataList) {
                if (operateId.equals(bean.user_id)) {
                    //找到取消的bean
                    cancelPosition = dataList.indexOf(bean);
                    break;
                }
            }
        }
        int visiblePostion = dataListview.getFirstVisiblePosition();
        if (cancelPosition - visiblePostion >= 0) {
            View view = dataListview.getChildAt(cancelPosition - visiblePostion).findViewById(R.id.check_select);
            if (view != null && view instanceof CheckBox) {
                ((CheckBox) view).setChecked(isSelectCancel);
            }
        }
    }

    @Override
    public void onEventMainThread(Map inParam) {
        super.onEventMainThread(inParam);
        if (inParam.get(EventBusConstant.TYPE) == null) {
            return;
        }
        String type = inParam.get(EventBusConstant.TYPE).toString();
        LogUtil.d(TAG, "wubaojie>>>onEventMainThread: type:" + type);
        if (type.equals(EventBusConstant.ACTIVITY_TO_ADDRESSBOOK)) {
            String id = (String) inParam.get(EventBusConstant.OPERATE_ID);
            updateBeanById(id, false);
        } else if (type.equals(EventBusConstant.ORGANIZATION_TO_ADDRESSBOOK)) {
            boolean isSelectCancel = (Boolean) inParam.get(EventBusConstant.SELECT_OR_CANCEM);
            String numberSelect = (String) inParam.get(EventBusConstant.NUMBER_SELECT);
            if (EventBusConstant.SINGLE_MEMBER.equals(numberSelect)) {
                String id = (String) inParam.get(EventBusConstant.OPERATE_ID);
                //选择单个
                updateBeanById(id, isSelectCancel);
            } else if (EventBusConstant.LIST_MEMBER.equals(numberSelect)) {
                //选择多个
                List<OrgDeptUserBean> operateList = (List<OrgDeptUserBean>) inParam.get(EventBusConstant.LIST_MEMBER);
                int index = 0;
                for (OrgDeptUserBean oldBean : dataList) {
                    for (OrgDeptUserBean newNean : operateList) {
                        if (oldBean != null && oldBean.user_id.equals(newNean.user_id)) {
                            oldBean.isSelectd = isSelectCancel;
                            updateBeanById(oldBean.user_id, isSelectCancel);
                            break;
                        }
                    }
                    index++;
                }
            }
        }
//        if (inParam.get(EventBusConstant.TYPE).equals(EventBusConstant.ACTION_SELECT_MENBER_FRAGMENT)) {
//            if (EventBusConstant.CANCEL_MEMBER.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
//                OrgDeptUserBean bean = (OrgDeptUserBean) inParam.get(EventBusConstant.ACTION_VALUE);
//                if (dataList != null && dataList.contains(bean)) {
//                    bean.isSelectd = false;
////                    mDataList.remove(bean);
//                    int postion = dataList.indexOf(bean);
//                    LogUtil.d(postion + "");
//                    int visiblePostion = dataListview.getFirstVisiblePosition();
//                    LogUtil.d(visiblePostion + "");
//                    if (postion - visiblePostion >= 0) {
//                        View view = dataListview.getChildAt(postion - visiblePostion).findViewById(R.id.check_select);
//                        if (view != null && view instanceof CheckBox) {
//                            ((CheckBox) view).setChecked(false);
//                        }
//                    }
//                }
//            }
//        }
//
//        if (inParam.get(EventBusConstant.TYPE).equals(EventBusConstant.ACTION_SELECT_MEMBER_ACTIVITY)) {
//            //选择单个
//            if (EventBusConstant.SINGLE_MEMBER.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
//                OrgDeptUserBean bean = (OrgDeptUserBean) inParam.get(EventBusConstant.ACTION_VALUE);
//                boolean isSelected = (Boolean) inParam.get(EventBusConstant.SELECT_OR_CANCEM);
//                int postion = 0;
//                for (int i = 0; i < dataList.size(); i++) {
//                    if (bean != null && bean.dept_id != null && bean.dept_id.equals(dataList.get(i).user_id)) {
//                        postion = i;
//                        break;
//                    }
//                }
//                LogUtil.d(postion + "");
//                updateListviewItem(postion, isSelected);
//            } else if (EventBusConstant.LIST_MEMBER.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
//                //选择多个
//                List<OrgDeptUserBean> addList = (List<OrgDeptUserBean>) inParam.get(EventBusConstant.ACTION_VALUE);
//                boolean isSelected = (Boolean) inParam.get(EventBusConstant.SELECT_OR_CANCEM);
//                for (OrgDeptUserBean bean : addList) {
//                    for (OrgDeptUserBean innerBean : dataList) {
//                        if (bean.dept_id.equals(innerBean.user_id)) {
//                            updateListviewItem(dataList.indexOf(innerBean), isSelected);
//                        }
//                    }
//                }
//                //选中
//            }
//        }
    }

    private void updateListviewItem(int postion, boolean isSelected) {
        int visiblePostion = dataListview.getFirstVisiblePosition();
        LogUtil.d(visiblePostion + "");
        if (postion - visiblePostion >= 0) {
            View view = dataListview.getChildAt(postion - visiblePostion).findViewById(R.id.check_select);
            if (view != null && view instanceof CheckBox) {
                ((CheckBox) view).setChecked(isSelected);
            }
        }
    }
}